package com.orion.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import com.orion.domain.SysUser;
import com.orion.service.impl.AuthUserDetailService;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @date 2021/8/24
 */
@Configuration
@EnableWebSecurity
public class AjaxSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "authUserDetailService")
    private AuthUserDetailService authUserDetailService;

    @Resource(name = "dataSource")
    private DataSource dataSource;

    @Resource(name = "verifyCodeSecurityConfig")
    private VerifyCodeSecurityConfig verifyCodeSecurityConfig;

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler(){
       return (request, response, exception) -> {
           response.setContentType("application/json;charset=utf-8");
           PrintWriter out = response.getWriter();
           System.out.println(exception.getMessage());
           out.write("{\"success\":false,\"message\":\"" + exception.getMessage() + "\"}");
           out.flush();
           out.close();
       };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //记住我 ,cookie配合数据库的
    @Bean
    public PersistentTokenRepository myPersistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        //jdbcTokenRepository.setCreateTableOnStartup(true);// 自动创建存放记住我的表,如果存在会报错
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.authenticationProvider(new VerifyCodeAuthenticationProvider());
        auth.userDetailsService(authUserDetailService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //http.apply(verifyCodeSecurityConfig);

        http.exceptionHandling().accessDeniedPage("/unauth").and()
                //.addFilterBefore(new VerifyCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new AjaxVerifyCodeFilter(authenticationFailureHandler()), UsernamePasswordAuthenticationFilter.class)

                .authorizeRequests()
                .antMatchers("/css*", "/js*", "/verifyCode/**").permitAll()
                //没角色显示页面403
                .antMatchers("/api").hasAnyAuthority("测试呢3", "测试呢4")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/myAjaxLogin")
                //自定义验证逻辑，增加验证码信息
                //.authenticationDetailsSource(customAuthenticationDetailsSource)
                .loginProcessingUrl("/haha").permitAll()
                .usernameParameter("uname")
                .passwordParameter("pwd")
                //前后分离用返回json
                .successHandler((req, resp, authentication) -> {
                    System.out.println(authentication.getCredentials());
                    System.out.println(authentication.getPrincipal());
                    System.out.println(authentication.getDetails());
                    System.out.println(authentication.getAuthorities());

                    SysUser sysUser = (SysUser) authentication.getPrincipal();

                    resp.setContentType("application/json;charset=utf-8");
                    System.out.println(sysUser);
                    PrintWriter out = resp.getWriter();
                    out.write("{\"success\":true,\"result\":\"登录成功\"}");
                    out.flush();
                    out.close();
                })
                .failureHandler((req, resp, exception) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    System.out.println(exception.getMessage());
                    out.write("{\"success\":false,\"message\":\"" + exception.getMessage() + "\"}");
                    out.flush();
                    out.close();
                }).and()
                //rememberMe记住我功能配置
                .rememberMe()
                .tokenValiditySeconds(60)
                .rememberMeParameter("rmb")
                .tokenRepository(myPersistentTokenRepository())
                .userDetailsService(authUserDetailService)
                .and()
                .logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/myAjaxLogin?logout")
                .and()
                .csrf().disable();
    }


}
